package cn.itcast.java.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Author itcast
 * Date 2021/10/10 17:58
 * 1.创建HashMap集合, 键是学生对象(Student), 值是居住地(String).
 * 2.往HashMap集合中添加3组数据.
 * 3.通过两种方式, 遍历HashMap集合.
 * 注意: HashMap集合想保证键的唯一性, 依赖hashCode()和equals()这两个方法.
 */
public class MapDemo02 {
    public static void main(String[] args) {
        Map<Student,String> ss = new HashMap<Student,String>();
        ss.put(
                new Student("zhangsan",20),
                "广东省深圳市宝安区"
        );
        ss.put(
                new Student("zhangsan",20),
                "广东省深圳市罗湖区"
        );
        for (Student key : ss.keySet()) {
            System.out.println(ss.get(key));
        }
    }
    public static class Student{
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        /**
         * 重写两个方法 equals 和 hashCode两个方法
         * equals 判断两个对象是否相等
         *  这两个对象中的成员变量的值是否相等，如果成员变量的值都相等，说明两个对象是相等的。
         */
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Student student = (Student) o;
            return age == student.age &&
                    Objects.equals(name, student.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, age);
        }
    }
}
